package com.heima.user.service;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.LoginDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.service.Impl.ApUserLoginService;
import com.heima.utils.common.AppJwtUtil;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.Map;

@Service
public class ApUserLoginServiceImpl extends ServiceImpl <ApUserMapper,ApUser> implements ApUserLoginService {


    @Override
    public ResponseResult login(LoginDto loginDto){
        // 正常登录
        if(loginDto.getPhone() != null && loginDto.getPassword() != null){

            // 获取到用户信息
            ApUser apUser = getOne(Wrappers.<ApUser>lambdaQuery().eq(ApUser::getPhone,loginDto.getPhone()));
            if(apUser == null){
                return ResponseResult.errorResult(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST);
            }

            // 获取到拼接之后的字符串
            String pwd = DigestUtils.md5DigestAsHex((loginDto.getPassword() + apUser.getSalt()).getBytes());

            // 密码正确就成功登录
            if(apUser.getPassword().equals(pwd)){
                String token = AppJwtUtil.getToken(apUser.getId().longValue());
                Map<String,Object> map = new HashMap<>();
                map.put("token",token);
                map.put("user",apUser);
                return ResponseResult.okResult(map);
            }

            // 密码错误就返回密码错误信息
            return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
        }

        // 游客登录
        Map<String,Object> map = new HashMap<>();
        map.put("token",AppJwtUtil.getToken(0L));
        return ResponseResult.okResult(map);
    }


}
